package logxx

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"go.uber.org/atomic"
	"math/rand"
	"payme3000/framework/errorx"
	"time"
)

var (
	harborId      = rand.New(rand.NewSource(time.Now().UnixNano())).Int63() % 128 // todo 暂时使用随机数
	packVersionId = atomic.NewInt64(0)
)

func MakePackVersion() int64 {
	packVersion := (harborId & 0xff) << 56
	packVersion += (int64(time.Now().Unix()) & 0xffffffffff) << 16 // 中间40位时间戳(秒)
	packVersion += packVersionId.Inc() & 0xffff                    // 最后16位自增id

	return packVersion
}

func NewLogContext(parent ...context.Context) context.Context {
	var ctx context.Context
	if len(parent) > 0 && parent[0] != nil {
		ctx = parent[0]
	} else {
		ctx = context.Background()
	}

	return logx.ContextWithFields(ctx, logx.Field("pack_version", MakePackVersion()))
}

func LogCrash(parent ...context.Context) {
	err := recover()
	if err == nil {
		return
	}

	var ctx context.Context
	if len(parent) > 0 && parent[0] != nil {
		ctx = parent[0]
	} else {
		ctx = context.Background()
	}

	// 打印调用栈信息
	errorx.Catch(ctx, err, 2)
}
